package world.snowcrystal.snowcrystalinterface.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        registry
//                .addInterceptor(new AccessInterceptor())
//                .addPathPatterns("/**");
    }


    static class AccessInterceptor implements HandlerInterceptor {


        public static final String ACCESS_KEY_HEADER = "X-Camellia-Access-Key";
        public static final String SECRET_KEY_HEADER = "X-Camellia-Secret-Key";
        public static final String AK_SK_SIGN = "X-Camellia-AK-SK-Sign";
        public static final String NONCE_HEADER = "X-Camellia-Nonce";
        public static final String TIMESTAMP_HEADER = "X-Camellia-Timestamp";


        private static final String SALT = "wqeiprqweioprhwsdjiofhndofhn";


        private MessageDigest instance;

        {
            try {
                instance = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException ignore) {
            }
        }

        private boolean match(String sign, String accessKey, String secretKey) {
            StringBuilder builder = new StringBuilder();
            builder.append(accessKey).append(secretKey).append(SALT);
            String userNonce = new String(Base64.getEncoder().encode(instance.digest(builder.toString().getBytes())));
            return userNonce.equals(sign);
        }

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {
            log.info("Request [{}] : ",request.getRequestId());
            final String sign;
            final String nonce;
            final Long timestamp;
            try {
                sign = request.getHeader(AK_SK_SIGN);
                nonce = request.getHeader(NONCE_HEADER);
                timestamp = Long.valueOf(request.getHeader(TIMESTAMP_HEADER));
            }catch (Exception e){
//                throw new RuntimeException("Invalid authentication information.");
                response.getWriter().write("Invalid authentication information.");
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return false;
            }
            if (System.currentTimeMillis() - timestamp > 10000L) {
                response.getWriter().write("EEE.Expired");
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return false;
            }
            //TODO 从数据库中根据当前登录用户获取对应的 accessKey 和 secretKey
            String accessKey = "hsadiufsdhvidufhvbuds";
            String secretKey = "123123123tianqing";

            if (!match(sign, accessKey, secretKey)) {
                response.getWriter().write("AccessKey or SecretKey is not correct");
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return false;
            }
            return true;
        }
    }

}
